package day19.pack9;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Station {
    private int count = 100;
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void getCount() {
        boolean isLock = false;
        try {
            isLock = lock.readLock().tryLock(1, TimeUnit.MILLISECONDS);
            if (isLock) {
                System.out.println(Thread.currentThread().getName() + "准备查询票数");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "剩余票数:" + count);
            } else {
                System.out.println(Thread.currentThread().getName() + "无法获取读锁，因为有人在写");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isLock) lock.readLock().unlock();
        }
    }

    public void sell() {
        boolean isLock = false;
        try {
            isLock = lock.writeLock().tryLock(1, TimeUnit.MILLISECONDS);
            if(isLock) {
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName()+"准备卖票");
                    Thread.sleep(500);
                    System.out.println("销售座位" + count-- + ",该票出售给了：" + Thread.currentThread().getName());
                } else {
                    System.out.println("抱歉，剩余票数为：" + count + ",当前线程为：" + Thread.currentThread().getName());
                    Thread.sleep(500);
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "无法获取写锁，因为有人在读或者写");
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (isLock) lock.writeLock().unlock();
        }
    }
}
